const handler = require('sv-handler')
const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
  // 题目列表
  async examList() {
    let {
      from_lib,
      unit,
      exam_id,
      exam_type,
      exam_title,
      exam_name,
      pagesize = 20,
      pagenum = 1,
    } = this.params

    // 转换为Number类型
    pagesize = +pagesize
    pagenum = +pagenum

    // 页码不可小于1
    if (pagenum < 1) {
      throw handler.result({
        code: 40001,
        message: 'pagenum不可小于1'
      })
    }

    let examRes, pages, total

    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo()
    })

    // 连接表实例
    let query = dbJQL.collection('sv-exam-list')

    // 全量查询
    if (pagesize < 1) {
      examRes = await query.get({
        getCount: true
      })
      // 总数统计
      total = examRes.count
      // 页数统计
      pages = Math.ceil(total / pagesize)

      throw handler.result({
        data: examRes.data,
        total,
        pagesize,
        pagenum,
        pages,
        params: this.params
      })
    }

    // 构建筛选条件(对象形式)
    const conditions = {}
    if (from_lib) {
      conditions.from_lib = dbCmd.eq(from_lib)
    }
    if (unit) {
      conditions.unit = dbCmd.eq(unit)
    }
    if (exam_id) {
      conditions.exam_id = dbCmd.eq(exam_id)
    }
    if (exam_type || exam_type === 0) {
      conditions.exam_type = dbCmd.eq(exam_type)
    }
    if (exam_title) {
      conditions.exam_title = new RegExp(exam_title.split('').join('.*'), 'i'); // 模糊查询
    }
    if (exam_name) {
      conditions.exam_name = new RegExp(exam_name.split('').join('.*'), 'i'); // 模糊查询
    }
    // 将所有有效的筛选条件添加到查询对象中
    if (Object.keys(conditions).length > 0) {
      query = query.where(conditions)
    }

    examRes = await query.orderBy('exam_index', 'asc')
      .skip(pagesize * (pagenum - 1)).limit(pagesize).get({
        getCount: true
      })

    total = examRes.count
    pages = Math.ceil(total / pagesize)

    return handler.result({
      data: examRes.data,
      total,
      pagesize,
      pagenum,
      pages,
      params: this.params
    })
  },
  // 更新题目
  async examUpdate() {
    const {
      exam_id,
    } = this.params

    if (!exam_id) {
      throw handler.result({
        code: 40001
      })
    }

    delete this.params._id // 移除_id字段，_id不参与更新
    const examRes = await db.collection('sv-exam-list').where({
      'exam_id': dbCmd.eq(exam_id)
    }).update(this.params)

    const isUpdated = examRes.updated
    if (!isUpdated) {
      // 没有更新则新增内容
      const examAddRes = await db.collection('sv-exam-list').add(this.params)
      throw handler.result({
        data: examAddRes,
        message: '未查询到更新项，已新增该项'
      })
    }

    return handler.result({
      data: examRes,
    })
  },
  // 添加题目
  async examAdd() {
    const {
      from_lib,
      unit,
      exam_id,
      exam_name,
      exam_type,
      exam_option,
      exam_answer
    } = this.params

    if (!exam_id || !from_lib || !exam_name || !exam_option || !exam_answer ||
      exam_type === null || exam_type === undefined || !unit) {
      throw handler.result({
        code: 40001
      })
    }

    const findExamRes = await db.collection('sv-exam-list').where({
      'exam_id': dbCmd.eq(exam_id)
    }).get()
    const isExist = findExamRes.affectedDocs
    if (isExist) {
      throw handler.result({
        code: 40003,
        message: '题目已存在'
      })
    }

    const examRes = await db.collection('sv-exam-list').add(this.params)

    return handler.result({
      data: examRes,
    })
  },

  // 批量添加
  async examAddList() {
    let {
      data,
      cover
    } = this.params

    if (!data || data.length <= 0) {
      throw handler.result({
        code: 40001
      })
    }

    const mainDB = 'sv-exam-list' // 主表
    const mainKey = 'exam_id' // 主键
    let filterData, mapData

    // 缺少必填参数exam_id的项不进行添加
    filterData = data.filter(item => item.exam_id)

    if (cover) {
      // 确认覆盖 先删后添加
      mapData = filterData.map(item => item[mainKey])
      let whereClause = {}
      whereClause[mainKey] = dbCmd.in(mapData)
      await db.collection(mainDB).where(whereClause).remove()
    } else {
      // 取消覆盖 先将filterData中已存在的移除
      const listRes = await db.collection(mainDB).get()
      mapData = listRes.data.map(item => item[mainKey])
      filterData = filterData.filter(item => mapData.indexOf(item[mainKey]) == -1)
    }

    if (filterData.length <= 0) {
      throw handler.result({
        code: 200,
        message: '没有数据更新'
      })
    }

    const addRes = await db.collection(mainDB).add(filterData)

    return handler.result({
      data: addRes,
    })
  },

  // 删除题目
  async examDelete() {
    const {
      exam_id
    } = this.params

    if (!exam_id) {
      throw handler.result({
        code: 40001
      })
    }

    const examRes = await db.collection('sv-exam-list').where({
      "exam_id": Array.isArray(exam_id) ? dbCmd.in(exam_id) : dbCmd.eq(exam_id)
    }).remove()

    return handler.result({
      data: examRes,
    })
  },
}